<template>
  <div>
    <div style="float:left;margin:10px">
      <el-button size="mini" type="primary" @click="addParentCategory()">添加一级分类</el-button>
    </div>

    <el-table
            ref="tableData"
            :data="categoryTree"
            style="width: 100%;margin-bottom: 20px;"
            row-key="id"
            size="mini"
            :default-expand-all="false"
            border
            :header-cell-style="{background:'#f2f3f7', color: '#333', textAlign: 'center'}"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="分类名" />
      <el-table-column prop="id" label="分类id" />
      <el-table-column label="是否同步商户" width="120" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.synMerchant">
            <el-tag size="mini" type="success">是</el-tag>
          </div>
          <div v-else>
            <el-tag size="mini" type="danger">否</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序"  align="center" />
      <el-table-column label="状态" width="80" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.status">
            <el-tag size="mini" type="success">启用</el-tag>
          </div>
          <div v-else>
            <el-tag size="mini" type="danger">禁用</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="describe" label="描述" />
      <!--            <el-table-column prop="categoryLevel" label="级别" width="50"></el-table-column>-->
      <!--      <el-table-column prop="createUser" label="创建人" width="100" />-->
      <el-table-column prop="createTime" label="创建时间" width="100" align="center" />
      <el-table-column label="操作" width="280" align="center">
        <template slot-scope="scope">
          <el-link style="font-size: 13px;" type="primary" @click="editCategory(scope.row)">编 辑<i class="el-icon-edit el-icon--right" /></el-link>
          <el-link style="margin-left: 10px;font-size: 13px;" type="primary" @click="delCategory(scope.row)">删 除<i class="el-icon-delete el-icon--right" /></el-link>
          <el-link v-if="scope.row.categoryLevel != 3" style="margin-left: 10px;font-size: 13px;" type="primary" @click="addChildCategory(scope.row)">新增子类<i class="el-icon-circle-plus-outline el-icon--right" /></el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
            title="分类详情"
            :visible.sync="addCategoryDialog"
            :close-on-click-modal="false"
            center
            @close="afterCategoryDialog()"
    >
      <div>

        <el-form ref="categoryForm" class="normalForm" :rules="rulesList" :model="addCategoryEntity">
          <div>
            <el-form-item label="父级分类" label-width="120px" class="fromBox">
              <el-input v-model="addCategoryEntity.parentName" size="small" style="width:120px;" :disabled="true" />
            </el-form-item>
            <el-form-item label="分类名称" prop="name" label-width="120px" class="fromBox">
              <el-input v-model="addCategoryEntity.name" size="small" style="width:120px;" placeholder="请输入分类名称" />
            </el-form-item>
          </div>
          <el-form-item label="分类展示图" label-width="120px" style="clear:both"><!--  :before-upload="beforeAvatarUpload" -->
            <el-upload
                    action=""
                    list-type="picture-card"
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :http-request="ossUpload"
                    :file-list="imgFilesList"
                    :limit="1"
                    :on-exceed="handleExceed"
            >
              <i class="el-icon-plus" />
<!--              <div slot="tip" class="el-upload__tip">分类图片只能上传大小小于200kb文件，且宽高等比例</div>-->
            </el-upload>
          </el-form-item>
          <el-form-item label="描述" label-width="120px">
            <el-input v-model="addCategoryEntity.describe" type="text" placeholder="请输入描述" />
          </el-form-item>
          <el-form-item label="排序" label-width="120px">
            <el-input v-model="addCategoryEntity.sort" type="text" placeholder="排序" />
          </el-form-item>
          <el-form-item label="备注" label-width="120px">
            <el-input v-model="addCategoryEntity.remark" type="text" placeholder="请输入备注" />
          </el-form-item>
          <el-form-item label="状态" label-width="120px">
            <el-radio v-model="addCategoryEntity.status" :label="true">启用</el-radio>
            <el-radio v-model="addCategoryEntity.status" :label="false">禁用</el-radio>
          </el-form-item>
          <el-form-item label="是否同步商家" label-width="120px" >
            <el-radio v-model="addCategoryEntity.synMerchant" :label="true">是</el-radio>
            <el-radio v-model="addCategoryEntity.synMerchant" :label="false">否</el-radio>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="addCategoryMethod()">确 定</el-button>
        <el-button size="mini" @click="addCategoryDialog = false">取消</el-button>
      </div>
    </el-dialog>
    <!--    <el-dialog append-to-body title="图片上传" :visible.sync="visible.img" @close="closeImgDialog">-->
    <!--      <Img ref="imgName" @imgInfo="getImgInfo" />-->
    <!--    </el-dialog>-->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import { productAjax, sysAjax } from 'Ajax'
  const { categoryTree, delCatById, addCat, editCat } = productAjax
  const axios = require('axios')
  export default {
    name: 'Category',
    // components: {
    //   Img
    // },
    data() {
      return {
        loading: false,
        categoryTree: [],
        type: 'add',
        addCategoryDialog: false,
        addCategoryEntity: { status: true, shelves: true },
        isExpand: false,
        // 图片信息
        // visible: {
        //   img: false,
        //   previewImag: false
        // },
        // imgUrl: '',
        dialogImageUrl: '',
        dialogVisible: false,
        imgFilesList: [],
        rulesList: {
          name: [{ required: true, message: '请输入分类名', trigger: 'blur' }]
        }
      }
    },
    created() {
      this.getCategoryTree()
    },
    methods: {
      getCategoryTree() {
        this.loading = true
        categoryTree().then(response => {
          this.categoryTree = response
          this.loading = false
        })
      },
      addParentCategory() {
        this.addCategoryEntity.parentId = 0
        this.addCategoryEntity.parentName = '无'
        this.addCategoryEntity.categoryLevel = 1
        this.type = 'add'
        this.addCategoryDialog = true
      },
      addChildCategory(row) {
        this.addCategoryEntity.parentId = row.id
        this.addCategoryEntity.parentName = row.name
        this.addCategoryEntity.categoryLevel = Number(row.categoryLevel) + 1
        this.type = 'add'
        this.addCategoryDialog = true
      },
      editCategory(row) {
        debugger
        this.addCategoryEntity = JSON.parse(JSON.stringify(row))
        this.type = 'edit'
        if (this.isNotBlank(this.addCategoryEntity.pictureUrl)) {
          const imgEntity = { url: this.addCategoryEntity.pictureUrl }
          this.imgFilesList.push(imgEntity)
        }

        this.addCategoryDialog = true
      },
      delCategory(row) {
        if (row.children != null && row.children.length > 0) {
          this.msgError('有子分类不能删除')
          return
        }

        const _this = this
        this.loading = true
        delCatById({ catId: row.id }).then(response => {
          this.msgSuccess('删除成功')
          _this.getCategoryTree()
        })
      },
      addCategoryMethod() {
        this.$refs['categoryForm'].validate((valid) => {
          if (valid) {
            const _this = this
            if (this.type === 'add') {
              addCat(this.addCategoryEntity).then(response => {
                this.msgSuccess('添加成功')
                _this.addCategoryDialog = false
                _this.getCategoryTree()
              })
            } else {
              editCat(this.addCategoryEntity).then(response => {
                this.msgSuccess('编辑成功')
                _this.addCategoryDialog = false
                _this.getCategoryTree()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      afterCategoryDialog() {
        this.type = 'add'
        this.addCategoryEntity = { status: true, shelves: true }
        this.imgFilesList = []
        this.handleExpand()
      },
      isBlank(str) {
        if (str === '' || str == null || str === undefined) { // "",null,undefined
          return true
        }
        return false
      },
      isNotBlank(str) {
        if (this.isBlank(str)) {
          return false
        }
        return true
      },
      // 是否展开table(展开与折叠切换)
      handleExpand() {
        this.$nextTick(() => {
          this.forArr(this.categoryTree, false)
        })
      },
      // 遍历
      forArr(arr, isExpand) {
        arr.forEach(i => {
          // toggleRowExpansion(i, isExpand)用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
          this.$refs.tableData.toggleRowExpansion(i, isExpand)
          if (i.children) {
            this.forArr(i.children, isExpand)
          }
        })
      },
      // ----------------------------------上传图片-------------------------------------
      // dialogTableVisible(type, genre) {
      //   this.visible[type] = true
      // },
      // handleRemove(file) {
      //   this.$refs.uploadImg.uploadFiles = this.$refs.uploadImg.uploadFiles.filter((item) => {
      //     return item.uid !== file.uid
      //   })
      // },
      // handlePictureCardPreview(file) {
      //   this.imgUrl = file.url
      //   this.visible.previewImag = true
      // },
      // // 获取图片数据
      // getImgInfo(obj) {
      //   console.log('获取图片数据-----', obj)
      //   this.addCategoryEntity.pictureUrl = obj.filename
      // },
      // closeImgDialog() {
      //   this.$refs.imgName.clearUpload()
      // },
      // ----------------------------------新上传图片-------------------------------------
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
        console.log('url', this.dialogImageUrl)
      },
      beforeAvatarUpload(file) {
        // const width = 1024
        // const height = 1024
        // 上传图片前处理函数
        console.info(file.size)
        const isBig = !(file.size / 1024 >= 200)
        if (!isBig) {
          this.$message.error('上传图片必须小于200kb')
          return false
        }
        const isSize = new Promise(function(resolve, reject) {
          const _URL = window.URL || window.webkitURL
          const image = new Image()
          image.onload = function() {
            const valid = image.width === image.height
            valid ? resolve() : reject()
          }
          image.src = _URL.createObjectURL(file)
        }).then(() => {
                  return file
                }, () => {
                  this.$message.error('上传图片尺寸不符合,只能是宽高相同的图片')
                  return Promise.reject()
                }
        )
        return isSize
      },
      ossUpload(data) {
        const file = data.file
        console.log(file)

        const index = file.name.indexOf('.')
        const nameEnd = file.name.substr(index)

        sysAjax.getOssPolicy().then(res => {
          console.log('policy', res)

          const nameStart = new Date().getTime() + '' + Math.ceil(Math.random() * 100)
          const name = '/' + nameStart + nameEnd

          const sendData = new FormData()
          sendData.append('OSSAccessKeyId', res.accessKeyId)
          sendData.append('policy', res.policy)
          sendData.append('signature', res.signature)
          // sendData.append('keys', res.dir)
          sendData.append('key', res.dir + name)
          sendData.append('success_action_status', '200') // 指定返回的状态码
          sendData.append('callback', res.callback)
          sendData.append('type', 'image/jpeg')
          sendData.append('file', file)
          axios.post(res.host, sendData, {
            'Content-Type': 'multipart/form-data'
          }).then(ossRes => {
            console.log('file', ossRes.data.data)
            console.log('url', ossRes.data.data.filename)
            this.addCategoryEntity.pictureUrl = ossRes.data.data.filename
          })
        })
      },
      handleExceed(files, fileList) {
        this.$message.warning('商品分类图片仅限上传一张')
      }
    }
  }
</script>

<style scoped>
  .cardView{
    margin:10px 0 0 10px;
    background: lightblue;
  }
  .cardView >>> .el-card__body{
    text-align: center;
  }
  .imgBox{
    width: 90%;
    min-height: 180px;
    border: 1px solid black;
    border-radius: 6px;
    margin: 10px 0 10px 20px;
    padding: 10px;
  }
  .imgBox>img{
    width:160px;
    height: 160px;
    display:inline-block;
    margin-left: 18px;
    border: 1px dashed #ccc;
    border-radius: 9px;
  }
  .fromBox{
    float:left;
  }
  .normalForm >>> .el-form-item__label {
    font-weight:normal
  }
</style>
